//
//  ZoomView.m
//  YCSchool
//
//  Created by yanglinxia on 16/5/3.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  自定义可缩放的视图

#import "ZoomView.h"

typedef NS_ENUM(short, kZoomedViewStye) {
    kZoomedViewStyeDefault,       //用户定义的视图
    kZoomedViewStyeImageView,     //图片视图
    kZoomedViewStyeWebImage       //网络图片视图
};

@interface ZoomView ()<UIScrollViewDelegate>
@property (nonatomic, assign) kZoomedViewStye zoomedViewStyle;//缩放图片类型
@property (nonatomic, assign) BOOL allowZoomed;//是否能被缩放
@property (nonatomic, assign) BOOL zoomedViewResize;//是否修正尺寸
@property (nonatomic, assign) BOOL scaling;//内部修改缩放
@end

@implementation ZoomView

#pragma mark - 初始化
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if(self){
        self.maximumZoomScale = 3.5;                //默认最大可以放大3.5倍
        self.minimumZoomScale = 1.0;                //默认最小可以缩小至1倍
        self.canZoomed        = YES;                //默认是允许缩放的
        self.delegate         = self;
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator   = NO;
        
        self.tapGestureRecognizer = [[UITapGestureRecognizer alloc] init];
        
        if(self.tapGestureRecognizer != nil){
            self.tapGestureRecognizer.cancelsTouchesInView = NO;
            self.tapGestureRecognizer.numberOfTapsRequired = 2;
            [self.tapGestureRecognizer addTarget:self action:@selector(touchZoomScale:)];
            [self addGestureRecognizer:self.tapGestureRecognizer];
        }
    }
    return self;
}

//将要被缩放的视图
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.allowZoomed ? self.zoomedView : nil;
}

//缩放比例改变时
- (void)zoomScaleDidChange
{
    @synchronized(self)
    {
        if(self.scaling || !self.allowZoomed)
        {
            return;
        }
        
        self.scaling = YES;
        
        CGSize size = self.zoomedView.frame.size;
        
        if(!self.zoomedViewResize)
        {
            self.zoomedViewResize = YES;
            
            //获取当前的尺寸
            size  = self.bounds.size;
            
            //获取图片的尺寸
            CGSize imageSize = self.zoomedViewSize;
            
            if(imageSize.width > 0 && imageSize.height > 0){
                
                CGFloat scale = self.zoomScale; //获取当前缩放比例
                super.zoomScale = 1.0;          //将缩放比例恢复为1倍
                //真实宽度与显示宽度的比例
                float widthScale  =  size.width / imageSize.width;
                //真实高度与显示高度的比例
                float heightScale =  size.height / imageSize.height;
                
                if(widthScale > heightScale)
                { //固定高度，等比调整宽度
                    size.width  = imageSize.width  * heightScale;
                    
                    if(size.width > 0)
                    {
                        self.maximumZoomScale = 3 * self.bounds.size.width / size.width;
                    }
                    else
                    {
                        self.maximumZoomScale = 3;
                    }
                }
                else
                { //固定宽度，等比调整高度
                    size.height = imageSize.height * widthScale;
                    
                    if(size.height > 0)
                    {
                        self.maximumZoomScale = 3 * self.bounds.size.height / size.height;
                    }
                    else
                    {
                        self.maximumZoomScale = 3;
                    }
                }
                
                size.width  *= self.zoomScale;
                size.height *= self.zoomScale;
                
                self.zoomedView.frame = CGRectMake(0, 0, size.width, size.height);
                //恢复缩放比例
                super.zoomScale = scale;
            }
        }
        
        UIEdgeInsets insets = UIEdgeInsetsZero;
        
        //当前视图尺寸
        CGSize viewSize = self.bounds.size;
        if(viewSize.width > size.width){
            insets.left = (viewSize.width - size.width) / 2.0;
        }
        if(viewSize.height > size.height){
            insets.top = (viewSize.height - size.height) / 2.0;
        }
        
        self.contentInset = insets;
        self.scaling = NO;
    }
}

//修改缩放比例
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    [self zoomScaleDidChange];
}

//结束缩放
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    if(scale == 1.0)
    {
        scrollView.contentSize = CGSizeMake((NSInteger)(ceil(view.bounds.size.width)), 0);
    }
}
//手动改变缩放比例
- (void)setZoomScale:(CGFloat)zoomScale
{
    super.zoomScale = zoomScale;
    [self zoomScaleDidChange];
}

//设置缩放视图
- (void)setZoomedView:(UIView *)zoomedView{
    //取消图片的加载
    if(self.zoomedViewStyle == kZoomedViewStyeWebImage){
        [((UIImageView *)self.zoomedView) sd_cancelCurrentImageLoad];
    }
    //删除前一个视图显示状态
    [self.zoomedView removeFromSuperview];
    
    //设置当前的视图类型
    self.zoomedViewStyle = kZoomedViewStyeDefault;
    
    _zoomedView = zoomedView;
    
    if(self.zoomedView != nil){
        //显示子视图
        [self addSubview:self.zoomedView];
    }
    
    //默认不允许触发事件
    //zoomedView.userInteractionEnabled = NO;
    //自动适应宽高
    zoomedView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    //视图居中
    zoomedView.contentMode = UIViewContentModeScaleAspectFill;
}

//设置缩放图片
- (void)zoomImage:(UIImage *)image{
    if(self.zoomedViewStyle == kZoomedViewStyeWebImage){
        //取消图片的加载
        [((UIImageView *)self.zoomedView) sd_cancelCurrentImageLoad];
    }
    //如果不是图片视图,则创建之
    else if(self.zoomedViewStyle != kZoomedViewStyeImageView && image != nil){
        self.zoomedView = [[UIImageView alloc]init];
        
        self.zoomedViewStyle = kZoomedViewStyeImageView;
    }
    ((UIImageView *)self.zoomedView).image = image;
    //设置图片
    [self finishedLoadImage:image];
}

//设置缩放网络图片
- (void)zoomImageWithURLString:(NSString *)urlString
{
    [self zoomImageWithURLString:urlString placeholderImage:nil];
}

- (void)zoomImageWithURLString:(NSString *)urlString placeholderImage:(UIImage *)image
{
    //获取网络图片加载视图
    UIImageView *subview = (UIImageView *)self.zoomedView;
    //如果不是网络图片模式,则创建对应视图
    if(self.zoomedViewStyle != kZoomedViewStyeWebImage)
    {
        subview = [[UIImageView alloc]initWithFrame:self.bounds];
        //设置图片加载完成的回调
//        [subview imageChangeAction:@selector(finishedLoadImage:) forTarget:self];
        self.zoomedView = subview;
        self.zoomedViewStyle = kZoomedViewStyeWebImage;
    }
    
    [subview sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:image completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [self finishedLoadImage:image];
    }];
}

- (void)normal
{
    self.scaling = YES;
    if(self.zoomScale != 1.0){
        super.zoomScale       = 1.0;
    }
    self.contentInset     = UIEdgeInsetsZero;
    self.zoomedView.frame = self.bounds;
    //未修正尺寸
    self.zoomedViewResize = NO;
    self.contentSize      = self.bounds.size;
    self.scaling          = NO;
}

//加载图片完成
- (void)finishedLoadImage:(UIImage *)image
{
    //加载默认的视图
    if(self.zoomedViewStyle == kZoomedViewStyeDefault)
    {
        return;
    }
    
    //是否允许缩放
    self.allowZoomed = (image != nil);
    
    self.zoomedViewSize = image.size;
    
    if(self.allowZoomed && self.canZoomed)
    {
        self.zoomedViewResize = NO;
        self.zoomScale = 1.0;
    }
    else
    {
        [self normal];
    }
}

//双击时进放大或者缩放
- (void)touchZoomScale:(UITapGestureRecognizer *)sender
{
    if(self.zoomScale == self.minimumZoomScale)
    {
        CGPoint point = [sender locationInView:self];
        [self zoomToRect:CGRectMake(point.x, point.y, 0, 0) animated:YES];
    }
    else
    {
        [self setZoomScale:self.minimumZoomScale animated:YES];
    }
}


@end
